import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:background_service_chengbie/app_retain_widget.dart';
import 'package:background_service_chengbie/background_main.dart';
import 'package:background_service_chengbie/counter_service.dart';

void main() {
  runApp(MyApp());

  //可以在没有FlutterActivity运行的情况下运行 Dart 代码
  var channel = const MethodChannel('com.example/background_service');
  //参考文档：https://flutter.dev/docs/development/packages-and-plugins/background-processes
  //题外话：
  //    偶然发现个Flutter 插件，用于访问 Android AlarmManager 服务，并在警报触发时在后台运行 Dart 代码。
  //https://pub.dev/packages/android_alarm_manager_plus

  //该backgroundMain方法将在后台 Isolate 启动时执行。
  //它的作用类似于 Flutter 应用程序启动时首先执行的 main 方法
  var callbackHandle = PluginUtilities.getCallbackHandle(backgroundMain);
  channel.invokeMethod('startService', callbackHandle.toRawHandle());

  CounterService.instance().startCounting();
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter后台运行',
      home: AppRetainWidget(
        child: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter后台运行'),
      ),
      body: Center(
        child: ValueListenableBuilder(
          //监听到数据，数据类型为ValueNotifier
          valueListenable: CounterService.instance().count,
          //在数据发生变化时调用，共有3个参数，分别表示context、数据新的值、子控件。
          builder: (context, count, child) {
            return Text('Counting: $count');
          },
        ),
      ),
    );
  }
}
